package com.ikun.mallbackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ikun.mallbackend.constant.SystemConstant;
import com.ikun.mallbackend.entity.Order;
import com.ikun.mallbackend.entity.OrderDetail;
import com.ikun.mallbackend.entity.Result;
import com.ikun.mallbackend.enums.OrderStateEnum;
import com.ikun.mallbackend.service.IOrderDetailService;
import com.ikun.mallbackend.service.IOrderService;
import com.ikun.mallbackend.util.DateUtil;
import com.ikun.mallbackend.util.JwtUtils;
import io.jsonwebtoken.Claims;
import javafx.scene.input.TouchEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 订单Controller控制器
 * @author java1234_小锋
 * @site www.java1234.com
 * @company 南通小锋网络科技有限公司
 * @create 2022-04-05 9:26
 */
@RestController
@RequestMapping("/my/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderDetailService orderDetailService;

    /**
     * 创建订单，返回订单号
     * @param token
     * @return
     */
    @RequestMapping("/create")
    @Transactional
    public Result create(@RequestBody Order order, @RequestHeader(value = "token")String token){
        // 通过token获取openid
        System.out.println("token="+token);
        System.out.println("order="+order);
        // 添加订单到数据库
        Claims claims = JwtUtils.validateJWT(token).getClaims();
        if(claims!=null){
            System.out.println("openid="+claims.getId());
            order.setUserId(claims.getId());
        }
        order.setOrderNo("JAVA"+DateUtil.getCurrentDateStr());
        order.setCreateDate(new Date());
        order.setStatus(OrderStateEnum.WAITING_FOR_PAYMENT.getCode()); // 设置初始状态为待付款

        OrderDetail[] goods = order.getGoods();
        orderService.save(order);
        // 添加订单详情到数据库
        for (OrderDetail good : goods) {
            good.setMId(order.getId());
            orderDetailService.save(good);
        }
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("orderNo",order.getOrderNo());
        return Result.ok(resultMap);
    }

    /**
     * 获取订单列表
     * @param type 0：查询全部订单；1：待付款；2：待收货；3：退款/退货
     * @return
     */
    @GetMapping("/list")
    public Result<Object> list(Integer type){
        List<Order> orderList = null;
        if(type != null){
            if(type == 0){
                // 查询全部订单
                orderList = orderService.list(new QueryWrapper<Order>().orderByDesc("id"));
            }else{
                orderList = orderService.list(new QueryWrapper<Order>().eq("status",type));
            }
        }
        return Result.ok(orderList);
    }
}
